﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using PTop.Application.WeChat;
using PTop.Code;

namespace PTop.Front.Areas.Wechat.Models
{
    public class WeChatCommon
    {
        /// <summary>
        /// 加密签名
        /// </summary>
        public const string SIGNATURE = "signature";
        /// <summary>
        /// 时间戳
        /// </summary>
        public const string TIMESTAMP = "timestamp";
        /// <summary>
        /// 随机数
        /// </summary>
        public const string NONCE = "nonce";
        /// <summary>
        /// 随机字符串
        /// </summary>
        public const string ECHOSTR = "echostr";

        /// <summary>
        /// 发送人
        /// </summary>
        public const string FROM_USERNAME = "FromUserName";
        /// <summary>
        /// 开发者微信号
        /// </summary>
        public const string TO_USERNAME = "ToUserName";
        /// <summary>
        /// 消息内容
        /// </summary>
        public const string CONTENT = "Content";
        /// <summary>
        /// 消息创建时间 （整型）
        /// </summary>
        public const string CREATE_TIME = "CreateTime";
        /// <summary>
        /// 消息类型
        /// </summary>
        public const string MSG_TYPE = "MsgType";
        /// <summary>
        /// 消息id，64位整型
        /// </summary>
        public const string MSG_ID = "MsgId";


        public const string EVENT = "Event";
        public const string EVENT_KEY = "EventKey";
        public const string TICKET = "Ticket";

        /// <summary>
        /// 微信appid(配置节中如果没有此配置,则使用默认的正式配置,使用测试号测试时需要单独加到配置节中)
        /// </summary>
        public string WECHAT_APPID
        {
            get
            {
                var appId = Configs.GetValue("WeChatAppId");
                return appId;
            }
        }

        /// <summary>
        /// 微信appsecret(配置节中如果没有此配置,则使用默认的正式配置,使用测试号测试时单独需要加到配置节中)
        /// </summary>
        public string WECHAT_APPSECRET
        {
            get
            {
                return Configs.GetValue("WeChatAppSecret");
            }
        }

        /// <summary>
        /// 微信web js配置
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, string> GetWxConfigDictionary(string url)
        {
            var api = new WxApiApp();
            var ticket = api.GetTiket();
            var dic = new Dictionary<string, string>
            {
                {"jsapi_ticket",ticket},
                {"noncestr",CreateRandomCode(16)},
                {"timestamp",GetTimeSpan()},
                {"url",url},
            };
            var str = CreateLinkString(dic);
            dic.Add("rawString", str);
            dic.Add("signature", SHA1(str).ToLower());
            return dic;
        }


        #region Private Methods

        /// <summary>
        /// 得到当前时间（整型）（考虑时区）
        /// </summary>
        /// <returns></returns>
        public static string GetNowTime()
        {
            DateTime timeStamp = new DateTime(1970, 1, 1);  //得到1970年的时间戳
            long a = (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000000;
            return a.ToString();
        }

        /// <summary>
        /// 获得时间戳
        /// </summary>
        /// <returns></returns>
        private string GetTimeSpan()
        {
            System.TimeSpan timestamp = DateTime.Now - Convert.ToDateTime("1970-01-01");
            double secs = timestamp.TotalSeconds;
            return Convert.ToUInt32(secs).ToString();
        }

        private string SHA1(string mystr)
        {
            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();
            //将mystr转换成byte[]
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(mystr);
            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);
            //将运算结果转换成string
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");
            return hash;
        }

        /// <summary>
        /// 创建随机数
        /// </summary>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        private static string CreateRandomCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;
            Random random = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    random = new Random(i * temp * (int)DateTime.Now.Ticks);
                }
                int t = random.Next(35);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[temp];
            }
            return randomCode;
        }

        /// <summary>
        /// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        /// </summary>
        /// <param name="dicArray">需要拼接的数组</param>
        /// <returns>拼接完成以后的字符串</returns>
        private static string CreateLinkString(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (KeyValuePair<string, string> temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }
            int nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);
            return prestr.ToString();
        }

        #endregion

    }
}